﻿using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.List.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.ListBillPlugin.BPW
{
    [Description("自定义单据，取消标准列表双击事件，改成直接下推采购订单变更单，修改确认参数，并打开对应的变更单.--列表插件"), HotUpdate]
    public class DoubleClickPush : AbstractListPlugIn
    {
        public override void ListRowDoubleClick(ListRowDoubleClickArgs e)
        {
            base.ListRowDoubleClick(e);
            string rule = "PUR_PurchaseOrder-PUR_POChange";
            var billno = this.ListView.CurrentSelectedRowInfo.BillNo;
            string numbers = string.Empty;
            var getPurResult = WebApiServiceCall.ExecuteBillQuery(this.Context, GetPurNoParm(billno));
            numbers = getPurResult[0][0].ToString();
            var poFid = WebApiServiceCall.ExecuteBillQuery(this.Context, GetPoFidParm(numbers));
            int purFid = Convert.ToInt32(poFid[0][0]);
            var isUnAudit = WebApiServiceCall.ExecuteBillQuery(this.Context, GetIsUnAudit(purFid));
            List<string> list = new List<string>();
            if (isUnAudit.Count > 0)
            {
                foreach (var item in isUnAudit)
                {
                    list.Add(item.ToString());
                }
            }
            list = list.Distinct().ToList();
            if (list.Count > 0)
            {
                foreach (var itemBillno in list)
                {
                    var del = WebApiServiceCall.Delete(this.Context, "PUR_POChange", GetDeleteParm(itemBillno));
                }
            }
            var res = JsonConvert.SerializeObject(WebApiServiceCall.Push(Context, "PUR_PurchaseOrder", GetPushParamStr(numbers, rule)));
            JObject result = JObject.Parse(res);
            var isSuccess = result["Result"]["ResponseStatus"]["IsSuccess"].Value<bool>();
            if (isSuccess)
            {
                var pkId = result["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"].Value<string>();
                bool save = true;
                if (save)
                {
                    var poEntryResult = WebApiServiceCall.ExecuteBillQuery(this.Context, GetPoEntityDataParm(billno));
                    var douSeveResult = WebApiServiceCall.ExecuteBillQuery(this.Context, GetQeuryParamStr(pkId));
                    foreach (var entry in douSeveResult)
                    {
                        foreach (var poEnti in poEntryResult)
                        {
                            if (Convert.ToInt32(entry[1]) == Convert.ToInt32(poEnti[0]))
                            {
                                var saveResult = WebApiServiceCall.Save(this.Context, "PUR_POChange", GetSaveParamStr(pkId, entry[0].ToString(), Convert.ToDecimal(poEnti[1]), Convert.ToDecimal(poEnti[2]), Convert.ToDateTime(poEnti[3])));
                            }
                        }
                    }

                }
                string pageId = Guid.NewGuid().ToString();
                BillShowParameter showParameter = new BillShowParameter();
                showParameter.FormId = "PUR_POChange";
                showParameter.OpenStyle.ShowType = ShowType.Default;
                showParameter.PageId = pageId;
                showParameter.Status = OperationStatus.EDIT;
                showParameter.PKey = pkId;
                this.View.ShowForm(showParameter);
                e.Cancel = true;
            }
            else
            {
                var err = result["Result"]["ResponseStatus"]["Errors"][0]["Message"].Value<string>();
                this.View.ShowErrMessage("下推采购订单变更单不成功，原因为：" + err);
                e.Cancel = true;
            }
        }

        private string GetDeleteParm(string itemBillno)
        {
            var param = new
            {
                Numbers = itemBillno
            };
            return JsonConvert.SerializeObject(param);
        }

        private string GetIsUnAudit(int purFid)
        {
            var param = new
            {
                FormId = "PUR_POChange",
                FieldKeys = "fbillno",
                FilterString = $@"FOFid={purFid} and FDocumentStatus<>'C'"
            };
            return JsonConvert.SerializeObject(param);
        }

        private string GetPoFidParm(string numbers)
        {
            var param = new
            {
                FormId = "PUR_PurchaseOrder",
                FieldKeys = "fid",
                FilterString = "fbillno=" + numbers
            };
            return JsonConvert.SerializeObject(param);
        }

        private string GetPoEntityDataParm(string billno)
        {
            var param = new
            {
                FormId = "XRIS_PurchaseConfirmation",
                FieldKeys = "FPURENTRYID,FQUANTITY,FPRICE_AMOUNT,F_BPW_CREATEDATE",
                FilterString = "fbillno=" + billno
            };
            return JsonConvert.SerializeObject(param);
        }
        private string GetPurNoParm(string billno)
        {
            var param = new
            {
                FormId = "XRIS_PurchaseConfirmation",
                FieldKeys = "FORDER_ID",
                FilterString = "fbillno=" + billno
            };
            return JsonConvert.SerializeObject(param);
        }
        /// <summary>
        /// 构建目标单据数据包，用于下推后对目标单据进行修改
        /// </summary>
        /// <param name="num"></param>
        /// <param name="entryid"></param>
        /// <returns></returns>
        private string GetSaveParamStr(string num, string entryid, decimal cfQty, decimal cfPrice, DateTime cfDate)
        {
            JObject param = new JObject();
            param.Add("Creator", "");
            JArray needUpdateFields = new JArray();
            needUpdateFields.Add("FEntity");
            needUpdateFields.Add("FNQty");
            needUpdateFields.Add("FNPrice");
            needUpdateFields.Add("FNDeliveryDate");
            param.Add("NeedUpDateFields", needUpdateFields);
            param.Add("NeedReturnFields", new JArray());
            param.Add("IsDeleteEntry", false);
            param.Add("SubSystemId", "");
            param.Add("IsVerifyBaseDataField", false);
            param.Add("IsEntryBatchFill", true);
            param.Add("ValidateFlag", true);
            param.Add("NumberSearch", true);
            param.Add("InterationFlags", "");
            JObject order = new JObject();
            param.Add("Model", order);
            order.Add("FID", num);
            JArray entity = new JArray();
            order.Add("FEntity", entity);
            JObject ent = new JObject();
            ent.Add("FENTRYID", entryid);
            ent.Add("FNQty", cfQty);
            ent.Add("FNPrice", cfPrice);
            ent.Add("FNDeliveryDate", cfDate);
            entity.Add(ent);
            return param.ToString();
        }
        /// <summary>
        /// 构建单据查询参数，用FID查询FENTRYID
        /// </summary>
        /// <param name="pkId"></param>
        /// <returns></returns>
        private string GetQeuryParamStr(string pkId)
        {
            var param = new
            {
                FormId = "PUR_POChange",
                FieldKeys = "FEntity_FEntryId,FOFEntryId",
                FilterString = "FID=" + pkId
            };
            return JsonConvert.SerializeObject(param);
        }
        /// <summary>
        /// 构建下推参数，Numbers为源单单据编号,RuleId为单据转换规则
        /// </summary>
        /// <param name="billno">源单单据编号</param>
        /// <param name="rule">单据转换规则</param>
        /// <returns></returns>
        public string GetPushParamStr(string billno, string rule)
        {
            var param = new
            {
                Numbers = new[] { billno },
                RuleId = rule
            };
            return JsonConvert.SerializeObject(param);
        }
    }
}
